
cc.Class({
    extends: cc.Component,

    properties: {
    },
    gameMgr:null,
    gameUIMgr:null,
    nowBot:null,
    inFinishArea:false,
    inDiscardArea:false,

    onLoad () {
        if(!cc.gg){
            cc.gg = {}
        }
        cc.gg.handPokerMgr = this

        cc.gg.registeListener("player_drag_poker_start",this._onPlayerDragPokerStart.bind(this),this)
        cc.gg.registeListener("player_drag_poker_move",this._onPlayerDragPokerMove.bind(this),this)
        cc.gg.registeListener("player_drag_poker_end",this._onPlayerDragEnd.bind(this),this)
        cc.gg.registeListener("player_click_poker",this._onPlayerClickPoker.bind(this),this)

        cc.gg.registeListener("start_group",this._onStartGroup.bind(this),this)
        // cc.find("Canvas").on("player_discard_passive",this._onPlayerDiscard.bind(this),this)

        this.selectedEndPokerNodeArray = []
    },

    start () {

    },

    update (dt) {},

    returnWaitDiscardNode:function () {
        if(this.waitDiscardNode){
            cc.log("cid改变，且仍然有等待出牌的牌节点,这张牌是：",this.waitDiscardNode.poker,"他应该回到手里")
            this.waitDiscardNode.getComponent("PokerModelTs").stopDraging()
            this.waitDiscardNode.getComponent("PokerModelTs").returnToOriginPos()
            cc.gg.handPokerMgr.setWaitDiscardNode(null)
        }
    },

    setWaitDiscardNode:function(pokerNode){
        cc.log("=======设置等待出牌牌节点11！",pokerNode)
        this.waitDiscardNode = pokerNode
    },

    initHandPokerParent:function (gameMgr, gameUIMgr, finishBounding, discardBounding) {
        if(!finishBounding || !discardBounding){
            cc.error("1asfasf")
            return
        }

        this.gameMgr = gameMgr
        this.gameUIMgr = gameUIMgr
        this.finishBox = finishBounding
        this.discardBox = discardBounding
    },

    _onPlayerDiscard:function () {
        if(!this.draggingNode) return
        this.draggingNode.getComponent("PokerModelTs").stopDraging()
        this.draggingNode.getComponent("PokerModelTs").returnToOriginPos()
    },

    _onStartGroup:function () {
        // this.selectingPokerNode = null
        this.selectedEndPokerNodeArray = []
        // this.resetAllPokerNode()
    },

    // resetAllPokerNode:function () {
    //     let pokerNoeds = cc.gg.tpgMgr.handPokerParent.children
    //
    //     for(let i=0;i<pokerNoeds.length;i++){
    //         cc.log("恢复卡牌状态",i)
    //         pokerNoeds[i].getComponent("PokerModelTs").cancelSelected()
    //     }
    // },

    _onPlayerClickPoker:function (clickNode) {
        this.draggingNode = null
        let pokerModelScript = clickNode.getComponent("PokerModelTs")
        if(pokerModelScript.fromDisPokerStack && pokerModelScript._disPokerDragable){
            pokerModelScript.setDisPokerAttr(false,false)
            cc.gg.emitEvent("player_grab_discarded_poker",cc.gg.dataMgr.getPlayerGameId(),clickNode,true)
            return
        }

        cc.logdrag("player click a poker")
        this._onPlayerClickePokerWhenGrouping(clickNode)
    },

    _onPlayerClickePokerWhenPlaying:function (clickNode) {
        let pokerNoeds = cc.gg.tpgMgr.handPokerParent.children

        let pokerModelScript = clickNode.getComponent("PokerModelTs")
        if(pokerModelScript._isSelected){
            pokerModelScript.cancelSelected()
            return
        }

        this.selectingPokerNode = clickNode
        for(let i=0;i<pokerNoeds.length;i++){
            if(clickNode === pokerNoeds[i]){
                clickNode.getComponent("PokerModelTs").showSelected()
            }else
                pokerNoeds[i].getComponent("PokerModelTs").cancelSelected()
        }
    },

    _onPlayerClickePokerWhenGrouping:function (clickNode) {
        let pokerModelScript = clickNode.getComponent("PokerModelTs")
        if(pokerModelScript._isSelected){
            pokerModelScript.cancelSelected()
            // this.selectedEndPokerNodeArray.remove(clickNode)
            cc.gg.baseUtil.arrayRemove(this.selectedEndPokerNodeArray,clickNode)
        }else {
            pokerModelScript.showSelected()
            cc.log("select poker node：",clickNode)
            this.addSelectedPoker(clickNode)
        }
        cc.find("Canvas").emit("option_select_node",this.selectedEndPokerNodeArray)
    },

    addSelectedPoker(clickNode){
        if(!cc.isValid(clickNode)){
            console.error("正在尝试向已选择手牌数组中添加一个无效的手牌节点！",clickNode)
            cc.gg.tdUtil.doSendTdEvent("debug_push_empty_selectnode")
            return
        }
        this.selectedEndPokerNodeArray.push(clickNode)
    },

    _onPlayerDragEnd:function (dragNode, endPos) {
        this.draggingNode = null
        this.gameUIMgr.showDisStackNotice(false,null)
        this.gameUIMgr.showFinishIndicator(false,null)


        let pokerModelScript = dragNode.getComponent("PokerModelTs")
        if(pokerModelScript.fromDisPokerStack && pokerModelScript._disPokerDragable)
        {
            let worldPos = dragNode.parent.convertToWorldSpaceAR(dragNode.position)
            if(!this._inGrabSuccessArea(worldPos)){
                cc.gg.emitEvent("player_grab_discarded_poker",cc.gg.dataMgr.playerId,dragNode)
                // pokerModelScript.returnToOriginPos()
            }else {
                this.gameMgr.playerCancelGrab(dragNode)
            }
            pokerModelScript.setDisPokerAttr(false,false)
            return
        }

        let bottoms = cc.gg.tpgMgr.bottomParent.children
        for(let i=0;i<bottoms.length;i++){
            let rectNode = bottoms[i].getComponent("SeperateBottom").bottomRect

            let tmpBoundingBox = rectNode.getBoundingBoxToWorld()

            if (tmpBoundingBox.contains(endPos)) {
                dragNode.getComponent("PokerModelTs").returnToOriginPos()
                return
            }
        }

        let backBounding = cc.gg.tpgMgr.bottomParent.getBoundingBoxToWorld()
        if (backBounding.contains(endPos)) {

            let rightBotNodepos = bottoms[bottoms.length-1].position
            let bottomNodeSpaceTouch = cc.gg.tpgMgr.bottomParent.convertToNodeSpaceAR(endPos)

            if(bottomNodeSpaceTouch.x > rightBotNodepos.x){
                cc.gg.emitEvent("add_bottom_to_right",this.nowBot,dragNode,cc.gg.tpgMgr.pokerBottoms.length)
                dragNode.getComponent("PokerModelTs").returnToOriginPos()
                return
            }
            else if(bottomNodeSpaceTouch.x < rightBotNodepos.x){
                cc.gg.emitEvent("add_bottom_to_left",dragNode)
                dragNode.getComponent("PokerModelTs").returnToOriginPos()
                return
            }
        }


        //check Finish
        let dragNodeWorldPos = dragNode.parent.convertToWorldSpaceAR(dragNode.position)
        if(!dragNode.getComponent("PokerModelTs").fromDisPokerStack && this.inFinishArea){//this.finishBox.contains(dragNodeWorldPos)
            if(cc.gg.tpgMgr.gameState === cc.gg.enumConfig.OptionState.PLAY){
                cc.gg.handPokerMgr.selectedEndPokerNodeArray = []
                cc.gg.handPokerMgr.addSelectedPoker(dragNode)

                this._sendTdFinish()
                cc.gg.emitEvent("opt_btn_finish",dragNode)
                return
            }
        }

        //check can discard or not
        if(this.inDiscardArea){//dragNodeWorldPos.y > backBounding.y + backBounding.height/2
            // this.inDiscardArea = false
            if(cc.gg.tpgMgr.canDiscard){
                this._sendTdDiscard()
                cc.gg.emitEvent("player_option_discard",dragNode)
            }else {
                cc.log("You can not discard in this duration")
                dragNode.getComponent("PokerModelTs").returnToOriginPos()
            }
        }else {
            dragNode.getComponent("PokerModelTs").returnToOriginPos()
        }
    },

    // _inGrabSuccessArea(pokerModel){
    //     if(!pokerModel.grabing) return false
    // },

    _inGrabSuccessArea(pokerWorldPos){
        if(!this._disDeckWorldY && this._disDeckWorldY !== 0) this._disDeckWorldY = cc.gg.tpgMgr.disPokerStack.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.disPokerStack).y

        if(pokerWorldPos.y > this._disDeckWorldY - cc.gg.tpgMgr.disPokerStack.height/2){
            return true
        }else {
            return false
        }

        return false
    },

    _sendTdDiscard:function () {
        let kv = {
            keys:["function"],
            values:["drag"]
        }
        let jsonStr = JSON.stringify(kv)
        cc.gg.tdUtil.doSendTdEvent("game_discard","Game",jsonStr)
    },

    _sendTdFinish:function () {
        let kv = {
            keys:["function"],
            values:["drag"]
        }
        let jsonStr = JSON.stringify(kv)
        cc.gg.tdUtil.doSendTdEvent("game_finish","Game",jsonStr)
    },

    _onPlayerDragPokerStart:function (dargNode,startPos) {
        this.inFinishArea = false
        this.inDiscardArea = false
        this.draggingNode = dargNode

        let pokerModelScript = dargNode.getComponent("PokerModelTs")
        if(pokerModelScript.fromDisPokerStack && pokerModelScript._disPokerDragable){
            cc.gg.emitEvent("player_start_grab_from_discards",dargNode,startPos)
        }

        let bot = this._getBottomWithPoker(dargNode.poker)
        if(!bot){
            cc.error("拖拽：找不到正在拖拽的牌",dargNode.poker,"所属的bottom")
            return
        }

        this.initDragingBottomPokerNodes(bot)
        this.nowBot = bot

        let pokers = bot.pokers
        let dragNodePokerIdxInBot = this._getPokerIdxInBot(bot,dargNode)
        if(dragNodePokerIdxInBot === -1){
            cc.error("拖拽：找不到正在拖拽的牌",dargNode.poker,"在bottom",bot,"中的index")
            return
        }

        let leftPoker = pokers[dragNodePokerIdxInBot-1] ? cc.gg.tpgMgr._getPokerNodeByPokerId(pokers[dragNodePokerIdxInBot-1].id) : null
        let rightPoker = pokers[dragNodePokerIdxInBot+1] ? cc.gg.tpgMgr._getPokerNodeByPokerId(pokers[dragNodePokerIdxInBot+1].id) : null

        let left = leftPoker?leftPoker.poker:null
        let right = rightPoker?rightPoker.poker:null
        let updateIt = false
        if(!this.insertJudgeObj)
        {
            cc.log("拖拽开始：当前没有判断Obj，更新")
            updateIt = true
        }else {
            //拖拽开始：判断Obj中的左右关系是否有什么不同
            updateIt = left !== this.insertJudgeObj.leftPoker || right !== this.insertJudgeObj.rightPoker
        }

        if(updateIt){
            this._setInsertJudgeObj(left,right,bot)
        }
    },

    _getPokerIdxInBot(nowBot,dargNode){
        let pokers = nowBot.pokers
        for(let i=0;i<pokers.length;i++){
            let pokerObj = pokers[i]
            let pokerNode = cc.gg.tpgMgr._getPokerNodeByPokerId(pokerObj.id)
            if(pokerNode === dargNode){
                return i
            }
        }
        return -1
    },

    _getBottomWithPoker(poker){
        let bot = null
        let bottoms = cc.gg.tpgMgr.bottomParent.children
        for(let i=0;i<bottoms.length;i++){
            if(!cc.isValid(bottoms[i],true))
                continue

            if (bottoms[i].botObj.pokers.indexOf(poker) > -1) {
                let inBotObj = bottoms[i].botObj

                bot = inBotObj
            }
        }
        return bot
    },

    //判断是否要显示弃牌区提示（弃牌堆上显示当前拖着的牌）
    _updateDisStackStatus(pokerNode, pokerWorldPos){
        // if(!this._backBounding) this._backBounding = cc.gg.tpgMgr.bottomParent.getBoundingBoxToWorld()
        if(!this._disDeckWorldY && this._disDeckWorldY !== 0) this._disDeckWorldY = cc.gg.tpgMgr.disPokerStack.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.disPokerStack).y

        if(pokerWorldPos.y > this._disDeckWorldY - cc.gg.tpgMgr.disPokerStack.height/2){
            if(cc.gg.tpgMgr.canDiscard){
                this.gameUIMgr.showDisStackNotice(true,pokerNode.poker.poker)
                return true
            }else {
                this.gameUIMgr.showDisStackNotice(false)
                return false
            }
        }else {
            this.gameUIMgr.showDisStackNotice(false)
            return false
        }

        return false
    },

    //按断是否要显示Finish区提示（Finish区显示当前拖着的牌）
    _updateFinishStackNotice(pokerNode,pokerWorldPos){
        if(!pokerNode.getComponent("PokerModelTs").fromDisPokerStack && cc.gg.tpgMgr.gameState === cc.gg.enumConfig.OptionState.PLAY){
            if(this.finishBox.contains(pokerWorldPos)){
                // cc.find("Canvas").emit("ui_show_discard_notice",false)
                let dragPokerFrame = pokerNode.getComponent(cc.Sprite).spriteFrame
                this.gameUIMgr.showFinishIndicator(true,dragPokerFrame)
                return true
            }else {
                this.gameUIMgr.showFinishIndicator(false,null)
                return false
            }
        }
        return false
    },

    //根据Bottom
    _updateBotPokersFromData(inBotObj,pokerNode){
        for(let i=0;i<inBotObj.pokers.length;i++){
            let pokerObj = inBotObj.pokers[i]
            let tmpPokerNode = cc.gg.tpgMgr._getPokerNodeByPokerId(pokerObj.id)
            tmpPokerNode.getComponent("PokerModelTs").cancelSelected()

            if(tmpPokerNode === pokerNode){
                let x = tmpPokerNode.x - inBotObj.width/2 + cc.gg.tpgMgr.bottomMarginLR + cc.gg.tpgMgr.pokerWidth/2 + i * cc.gg.tpgMgr.pokerInterval
                let y = tmpPokerNode.y + cc.gg.tpgMgr.pokerModel.data.height/2
                pokerNode.getComponent("PokerModelTs").setFromData(cc.v2(x,y),i,1)
            }
        }
    },

    _onPlayerDragPokerMove:function (pokerNode, event) {

        let pokerWorldPos = pokerNode.parent.convertToWorldSpaceAR(pokerNode.position)

        let pokerModel = pokerNode.getComponent("PokerModelTs")
        if(!pokerModel.fromDisPokerStack){
            //check if in finish area
            let showFinishIndicator = this._updateFinishStackNotice(pokerNode,pokerWorldPos)
            this.inFinishArea = showFinishIndicator
            //check can discard or not
            if(!showFinishIndicator){
                let showDiscardIndicator = this._updateDisStackStatus(pokerNode,pokerWorldPos)
                this.inDiscardArea = showDiscardIndicator
            }
        }

        let touchPos = event.getLocation()
        let touchingBottomObj = this._getTouchingBottom(pokerWorldPos)
        //拖拽到了一个新的Bottom
        if(touchingBottomObj !== "notcontain" && this.nowBot != touchingBottomObj){
            let dragPoker = pokerNode.poker
            cc.log("移动",cc.gg.dataMgr.getPokerName(dragPoker.poker))
            let addToLeftOrRight = this.nowBot.node.x < touchingBottomObj.node.x
            this._movePokerData(this.nowBot,touchingBottomObj,dragPoker,addToLeftOrRight)
            this.nowBot = touchingBottomObj
            // this.initDragingBottomPokerNodes(touchingBottomObj)
            //update draging node's return pos
            this._updateBotPokersFromData(touchingBottomObj,pokerNode)
            cc.gg.tpgMgr._onUpdateBottomsWidth(pokerNode)
            return
        }


        if(!this.insertJudgeObj){
            cc.error("insertJudgeObj has not been inited!")
            return
        }

        let botContainsPoker = this._getTouchingBottom(pokerWorldPos)
        if(botContainsPoker !== "notcontain"){
            //update pokers sequence
            let leftNode = null
            let rightNode = null
            let botNodes = this.getBottomPokerNodes(botContainsPoker)
            //get left and right node of draging node
            for(let j=0;j<botNodes.length;j++){
                let tmpNode = botNodes[j]

                if(tmpNode === pokerNode)
                    continue

                if(pokerNode.x < tmpNode.x){
                    if(!rightNode){
                        rightNode = tmpNode
                    }else {

                    }
                }else {
                    leftNode = tmpNode
                }
            }


            let left = leftNode?leftNode.poker:null
            let rrr = rightNode?rightNode.poker:null

            if(this.insertJudgeObj.bot === botContainsPoker){

                if(left !== this.insertJudgeObj.leftPoker || rrr !== this.insertJudgeObj.rightPoker)
                {
                    this.clearSelectedNodes()

                    // let newPokers = [].concat(botContainsPoker.pokers)
                    // let dragPoker = pokerNode.poker
                    // let removeSuccess = cc.gg.baseUtil.arrayRemove(newPokers,dragPoker)
                    // if(removeSuccess){
                    //     if(!left){
                    //         newPokers.unshift(dragPoker)
                    //     }else if(!rrr){
                    //         newPokers.push(dragPoker)
                    //     }else {
                    //         let rightOneIdx = newPokers.indexOf(rrr)
                    //         newPokers.splice(rightOneIdx,0,dragPoker)
                    //     }
                    //
                    //     cc.gg.tpgMgr._updateBottomPokersPositionWithChangeIdex(botContainsPoker,newPokers,pokerNode)
                    // }else {
                    //     cc.warn("移除没成功：",newPokers,"  要移除：",cc.gg.dataMgr.getPokerName(dragPoker.poker))
                    // }
                    this._updateBottomPokerPositions(botContainsPoker,pokerNode,left,rrr)
                    this._setInsertJudgeObj(left,rrr,botContainsPoker)
                }
            }else {
                this._setInsertJudgeObj(left,rrr,botContainsPoker)
            }
        }
    },

    _updateBottomPokerPositions(botContainsPoker,pokerNode,left,rrr){
        let newPokers = [].concat(botContainsPoker.pokers)

        let dragPoker = pokerNode.poker
        let removeSuccess = cc.gg.baseUtil.arrayRemove(newPokers,dragPoker)
        if(removeSuccess){
            if(!left){
                newPokers.unshift(dragPoker)
            }else if(!rrr){
                newPokers.push(dragPoker)
            }else {
                let rightOneIdx = newPokers.indexOf(rrr)
                newPokers.splice(rightOneIdx,0,dragPoker)
            }

            cc.gg.tpgMgr._updateBottomPokersPositionWithChangeIdex(botContainsPoker,newPokers,pokerNode)
        }else {
            cc.warn("移除没成功：",newPokers,"  要移除：",cc.gg.dataMgr.getPokerName(dragPoker.poker))
        }
    },

    _setInsertJudgeObj(left,rrr,botContainsPoker){
        this.insertJudgeObj = {
            leftPoker:left,
            rightPoker:rrr,
            bot:botContainsPoker
        }
    },

    _getTouchingBottom(touchPos){
        let bottoms = cc.gg.tpgMgr.bottomParent.children
        for(let i=0;i<bottoms.length;i++){
            let rectNode = bottoms[i].getComponent("SeperateBottom").bottomRect
            let tmpBoundingBox = rectNode.getBoundingBoxToWorld()

            if (tmpBoundingBox.contains(touchPos)) {
                let inBotObj = bottoms[i].botObj
                return inBotObj
            }
        }

        return "notcontain"
    },

    _movePokerData:function (fromBotObj, toBotObj, pokerObj,addToLeftOrRight) {
        cc.log("-------------------------From1----",JSON.stringify(fromBotObj.pokers))
        cc.log("-------------------------To1----",JSON.stringify(toBotObj.pokers))
        if(fromBotObj.pokers === toBotObj.pokers){
            cc.error("源数组和目标数组是同一个！")
            return
        }
        if(!cc.gg.baseUtil.arrayRemove(fromBotObj.pokers,pokerObj)){
            cc.error("移除失败！")
            return
        }

        if(addToLeftOrRight){
            toBotObj.pokers.unshift(pokerObj)
        }else toBotObj.pokers.push(pokerObj)
        cc.log("-------------------------From2----",JSON.stringify(fromBotObj.pokers))
        cc.log("-------------------------To2----",JSON.stringify(toBotObj.pokers))
    },

    clearSelectedNodes:function () {
        if(this.selectedEndPokerNodeArray.length){
            for(let k=0;k<this.selectedEndPokerNodeArray.length;k++){
                let node = this.selectedEndPokerNodeArray[k]
                if(cc.isValid(node)){
                    node.getComponent("PokerModelTs").cancelSelected()
                }

                this.selectedEndPokerNodeArray.splice(k--,1)
            }
            cc.find("Canvas").emit("option_select_node",this.selectedEndPokerNodeArray)
        }
    },


    initDragingBottomPokerNodes:function (inBotObj) {
        let group = inBotObj.pokers
        this.nowBotPokerNodes = []

        let lastNode1 = null
        for(let j=0;j<group.length;j++){
            let pokerNode = cc.gg.tpgMgr._getPokerNodeByPokerId(group[j].id)
            this.nowBotPokerNodes.push(pokerNode)

            pokerNode.preNode = lastNode1
            lastNode1 = pokerNode

            pokerNode.nextNode = group[j+1] || null
        }
    },

    getBottomPokerNodes:function (inBotObj) {
        let group = inBotObj.pokers
        let nowBotPokerNodes = []

        let lastNode1 = null
        for(let j=0;j<group.length;j++){
            let pokerNode = cc.gg.tpgMgr._getPokerNodeByPokerId(group[j].id)
            nowBotPokerNodes.push(pokerNode)

            pokerNode.preNode = lastNode1
            lastNode1 = pokerNode

            pokerNode.nextNode = group[j+1] || null
        }

        return nowBotPokerNodes
    },
});
